import { StyleSheet, View, Text, ImageBackground, Dimensions, SafeAreaView, TouchableHighlight, Alert } from 'react-native'
import React, { useEffect, useState } from 'react'
// 验证码组件
import {
	CodeField,
	Cursor,
	useBlurOnFulfill,
	useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import { Navigation } from 'react-native-navigation';
import { MainRoot } from '../navigation'
// 获取屏幕高度
const { width, height } = Dimensions.get('screen')
export default function InputAuthCode(props) {
	const { telValue } = props
	const [isActive, setIsActive] = useState(false)
	// 验证码数据
	const CELL_COUNT = 4;
	const [value, setValue] = useState('');
	const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT });
	const [props1, getCellOnLayoutHandler] = useClearByFocusCell({
		value,
		setValue,
	});
	// 提交请求：手机号 + 验证码
	const subMit = () => {
		if (!isActive) return
		// 跳转到主屏幕页面
		Navigation.setRoot(MainRoot)
	}
	// 获取验证码
	const getCode1 = () => {
		fetch('https://yd.ymyimi.cn:8543/api/yid/ydSyuserSms/sendLoginCode', {
			method: 'POST',
			body: JSON.stringify({ phone: telValue }),
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				'SYS_SIGN': 'APP',
			}
		}).then(res => res.json()).then(data => {
			console.log('data:', data);
			if (data.status === 1) {
				Alert.alert(data.result.message)
			}
		}).catch(err => {
			console.log('error:', err)
		})
	}
	// 判断是否输入了4位的验证码
	const checkValueLength = (text) => {
		setValue(text)
		if (text.length === 4) {
			setIsActive(true)
		} else {
			setIsActive(false)
		}
	}
	// 获取验证码
	const [timer, setTimer] = useState(60) // 定时器时间
	const [timerId, setTimerId] = useState(1) // 判断是否能够再次发送验证码
	const getCode = () => {
		if (timer !== 60) return
		setTimerId(timerId + 1)
	}
	useEffect(() => {
		// getCode1() // 需要获取验证码时解开注释
		let timeInte = setInterval(() => {
			setTimer(timer => {
				if (timer == 0) {
					clearInterval(timeInte)
					return timer = 60
				} else {
					return timer - 1
				}
			})
		}, 1000);
		return () => {
			// 清除定时器的副作用
			clearInterval(timeInte)
		};
	}, [timerId])


	return (
		<ImageBackground source={require('../assets/img/cat.jpg')} style={styles.bgImg}>
			<View style={styles.container}>
				{/* 顶部文字 */}
				<View style={styles.headContainer}>
					<Text style={styles.vText}>请输入验证码</Text>
					<Text style={styles.vText1}>已发送4位验证码到+86{telValue}</Text>
				</View>
				{/* 验证码输入框 */}
				<View style={{ display: 'flex', alignItems: 'center' }}>
					<SafeAreaView style={styles.root}>
						<CodeField
							ref={ref}
							{...props1}
							value={value}
							onChangeText={text => {
								checkValueLength(text)
							}}
							cellCount={CELL_COUNT}
							rootStyle={styles.codeFieldRoot}
							keyboardType="number-pad"
							textContentType="oneTimeCode"
							renderCell={({ index, symbol, isFocused }) => (
								<Text
									key={index}
									style={[styles.cell, isFocused && styles.focusCell]}
									onLayout={getCellOnLayoutHandler(index)}>
									{symbol || (isFocused ? <Cursor /> : null)}
								</Text>
							)}
						/>
					</SafeAreaView>
				</View>
				{/* 提交按钮 */}
				<View style={{ display: 'flex', alignItems: 'center' }}>
					<TouchableHighlight
						style={isActive && value.length === 4 ? styles.codeBtn : styles.codeBtn1}
						underlayColor='rgba(0,0,0,0.5)'
						activeOpacity={0.6}
						onPress={subMit}>
						<View>
							<Text style={{ color: 'white', fontSize: 18 }}>提交</Text>
						</View>
					</TouchableHighlight>
				</View>
				{/* 获取验证码, */}
				<TouchableHighlight
					underlayColor='rgba(25,25,25,0)'
					activeOpacity={0.6}
					onPress={getCode}
				>
					<Text style={styles.touchText}>重新获取（{timer}）</Text>
				</TouchableHighlight>

			</View>

		</ImageBackground>
	)
}
InputAuthCode.options = {
	topBar: {
		visible: false
	},
	statusBar: {
		visible: false
	}
}

const styles = StyleSheet.create({
	bgImg: {
		flex: 1,
		width: width,
		height: height,
	},
	container: {
		flex: 1,
		width: width,
		height: height,
		paddingLeft: 20,
		paddingRight: 20,
		backgroundColor: 'rgba(0,0,0,0.1)',
	},
	headContainer: {
		marginTop: 100,
	},
	vText: {
		color: 'white',
		fontSize: 20,
		fontWeight: 'bold',
		marginBottom: 5
	},
	vText1: {
		color: 'white',
		fontSize: 14,
	},
	// 验证码
	root: { flex: 1, padding: 20, width: 300 },
	title: { textAlign: 'center', fontSize: 30 },
	codeFieldRoot: { marginTop: 20 },
	cell: {
		width: 40,
		height: 40,
		lineHeight: 38,
		fontSize: 24,
		borderWidth: 2,
		color: 'white',
		borderColor: '#00000030',
		backgroundColor: '#00000040',
		textAlign: 'center',
	},
	focusCell: {
		borderColor: '#000',
	},
	// 提交按钮
	codeBtn: {
		width: 300,
		height: 60,
		borderRadius: 30,
		marginTop: 100,
		display: 'flex',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: 'rgba(0, 122, 204, 0.5)',
	},
	codeBtn1: {
		width: 300,
		height: 60,
		borderRadius: 30,
		marginTop: 100,
		display: 'flex',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: '#eeeeee60',
	},
	// 获取验证码
	touchText: {
		color: '#fff',
		textAlign: 'center',
		marginTop: 20,
		fontSize: 18
	}


})